<!-- 出库单创建 -->
<template>
  	<div class="page_rela_container">
		<div class="scroll_auto flex_cell">
    <el-form ref="form" :model="form" :label-width="$globalCss.formLabelWidth_default" :rules="formRules"
      v-loading="loading" label-position="right" class="common-form-panel-div">

      <ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>

      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_outbound_type')" prop="outType">
            <ex_super_input v-model="form.outType" type="select" enum="OmsOutboundOrderTypeEnum" style="width: 100%;"
              :listHandler="list => list.filter(it => ['SALES_OUTBOUND', 'DESTROY_OUTBOUND'].includes(it))"
              :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_business_type', '业务类型')" prop="bizType">
            <ex_super_input :value="form.bizType" type="select" enum="BizTypeEnum" style="width: 100%;"
              @change="changeBizType" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item :label="$t('label_outbound_warehouse')" prop="warehouseId">
            <ex_super_input :value="form.warehouseId" style="width: 100%;" :items="WarehouseList" :attrs="{
      option: (e) => ({ label: $formatNameCode(e.warehouseName, e.warehouseCode), value: e['warehouseId'] }),
    }" type="select" @changeItem="changeWarehouseConfirm" :disabled="GET_TRACK_NUMBER_FAIL" />
          </el-form-item>
        </el-col>

      </el-row>

      <!-- 退货单信息 -->
      <template v-if="SALES_OUTBOUND || DESTROY_OUTBOUND">
        <ex_header_spiler :title="$t('label_returnGood_info')"></ex_header_spiler>

        <el-row>
          <el-col :span="3">
            <el-form-item>

              <el-button :disabled="GET_TRACK_NUMBER_FAIL" @click="clickWarehouseSkuSelect" icon="el-icon-plus">
                <!--  type="primary" -->
                {{ $tt('label_new_returnGood_order') }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col style="width: 100%; max-width: 1400px; ">
            <el-form-item :label="$t('label_returnGood_detail')" prop="detailList">
              <ex_super_table v-bind="skuTableOption" :data="form.detailList" ref="TableSkuList">
              </ex_super_table>
            </el-form-item>
          </el-col>
        </el-row>

      </template>





      <el-row>
        <el-col :span="24">
          <el-form-item :label="$tt('label_remark')" prop="remark">
            <ex_super_input v-model="form.remark" type="input" :disabled="GET_TRACK_NUMBER_FAIL"
              :attrs="{ type: 'textarea', maxlength: 500, 'show-word-limit': true }"
              class="form_input_default-default" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <return_good_order_select ref="return_good_order_select" @submitSuccess="returnOrderSelect" />
  </div>
    <div class="page_rela_bottom_area" >
      <!-- <el-button type="primary" @click="submit('Save')">{{ $tt('label_save_to_draft') }}</el-button> -->
      <el-button type="primary" @click="submit('Submit')">{{ $tt('label_submit_and_audit') }}</el-button>
      <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
    </div>


  </div>
</template>


<script>

const defaultItemObj = {
  skuId: null,
  skuOnlyCode: null,
  skuBarcode: null,
  skuNameCn: null,
  skuNameEn: null,
  usableQty: null,
  stockCount: null,
  skuPackage: null,
  currencyCode: null,
  skuDeclaredValue: null,
  boxCount: null,
  skuCount: null,
}
let defaultObj = {

  bizType: 'TOC',
  customerId: -1,
  customerName: "-",
  customerCode: "-",
  ownerlessFlag: "Y",
  // ullageFlag: 'N',//
  // orderNo: null,// string 	出库单号
  ecPlatformOrderNo: null,// string 	平台单号
  ecPlatform: null,// OmsOutboundOrderEcPlatformEnum 	AliExpress:AliExpress, Amazon:Amazon, B2C:B2C, eBay:eBay, Wildberries:Wildberries, Ozon:Ozon, Other:Other
  outType: 'DESTROY_OUTBOUND',// OmsOutboundOrderTypeEnum 	SALES_OUTBOUND:销售出库, RETURN_OUTBOUND:退仓出库, ALLOCATE_OUTBOUND:调拨出库, DESTROY_OUTBOUND:销毁出库
  outStatus: null,// OmsOutboundOrderStatusEnum 	DRAFT:草稿, WAREHOUSE_PROCESSING:仓库处理中, COMPLETE_OUTBOUND:已出库, COMPLETED:已完成, EXCEPTION:异常, INVALID:已作废
  outboundMode: 'HOME_DELIVERY',
  warehouseId: null,// long 	出库仓库id
  warehouseCode: null,// string 	仓库编码
  warehouseName: null,
  logisticsId: null,// long 	物流产品id
  logisticsCode: null,// string 	物流产品编码
  logisticsName: null,// string 	物流产品名称
  deliveryType: null,// string 	派送方式
  shipmentId: null,// string 	ShipmentID
  referenceId: null,// string 	ReferenceID
  cutoffDate: null,// long 	截单时间
  cutoffReason: null,// string 	截单原因
  remark: null,// string 	备注

  payOnDelivery: null,// YesOrNoEnum 	Y:是, N:否
  signReceipt: null,// YesOrNoEnum 	Y:是, N:否
  // trackNumber: null,// string 	跟踪号
  insuranceService: 'N',// YesOrNoEnum 	Y:是, N:否
  insuranceAmount: null,// bigdecimal 	投保金额
  county: null,// string 	收货区县
  province: null,// string 	收货省份
  city: null,// string 	收货城市
  country: null,// string 	收货国家
  address: null,// string 	收货地址
  reserveAddress: null,// string 	收货地址2
  consignee: null,// string 	收货人
  consigneePhone: null,// string 	收货人电话
  email: null,// string 	收件人邮箱
  postcode: null,// string 	邮编
  houseNumber: null,// string 	门牌号
  companyName: null,// string 	公司名称
  fbaWarehouseId: null,// long 	fba仓库id
  fbaWarehouseCode: null,// string 	fba仓库code
  // outDate: null,// long 	出库时间
  detailList: [],//array<object> 	新增或修改的订单明细
  removeDetailIds: [],
  attachmentList: [],
  removeAttachmentIds: [],

  outboundProductType: 'PRODUCT_OUTBOUND',
  ecPlatformWarehouseId: null,
  ecPlatformWarehouse: null,
  // orderId 		long 	出库单id
  // boxNumber 		string 	外包装箱条码
  // skuId 		long 	skuid
  // skuOnlyCode 		string 	sku编码
  // skuNameCn 		string 	sku中文名称
  // skuNameEn 		string 	sku英文名称
  // skuCount 		integer 	出库数量
  // stockCount 		integer 	库存数量
  // trackNumber 		string 	跟踪号
  // totalWeight 		bigdecimal 	重量
  // totalVolume 		bigdecimal 	体积
}

import return_good_order_select from './dialog/return_good_order_select'
import router_params from '@/mixin/router_params';

import role_system_mixin from "@/mixin/role_system_mixin";
export default {

  mixins: [router_params, role_system_mixin],
  components: { return_good_order_select, },

  data() {
    return {
      edit: false,
      WarehouseList: [],
      ProductList: [],
      // editOrgSkuIdList: [],//编辑时保留原sku列表数据，后台删除skuid需要=。=
      loading: false,
      form: _.cloneDeep(defaultObj),

      requiredRule: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

      formRules: {

        outType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        bizType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        ullageFlag: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

        warehouseId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        logisticsId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

        detailList: { required: true, type: 'array', validator: this.skuListValidator, trigger: 'blur' },
      },

      skuTableOption: {
        model: [
          {
            key: 'returnOrderCode', label: 'label_return_order_code', "min-width": 150,
          },
          { key: 'storeCode', label: 'label_platform_store', 'show-overflow-tooltip': true, "width": 130, },
          {
            key: 'skuNameCn', label: 'label_sku_info', 'min-width': 140, 'show-overflow-tooltip': true
          },
          // { key: 'skuBarcode', label: 'label_sku_code', 'width': 140, 'show-overflow-tooltip': true, if: () => this.SkuOutbound, },
          {
            key: 'skuOnlyCode', label: 'label_sku_only_code', 'width': 220, if: () => this.SkuOutbound,
          },
          // {
          //   key: 'batchNo', label: 'label_batch_code', 'min-width': 140, 'show-overflow-tooltip': true
          // },
          {
            key: 'skuDeclaredValue', label: 'label_declared_value', 'width': 120, 'show-overflow-tooltip': true, if: () => this.SkuOutbound,
            formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
          },
          { key: 'stockUsage', label: 'label_stock_usage', 'width': 130, formatter: (r, c, v, i) => this.$enumShow(v, "StockUsageEnum") },
          { key: 'boxNo', label: 'label_box_code', 'min-width': 150, if: () => !this.SkuOutbound },
          { key: 'usableQty', label: 'label_sku_count', 'width': 120, if: () => !this.SkuOutbound },
          { key: 'usableQty', label: 'label_usable_count', 'width': 120, if: () => this.SkuOutbound },
          {
            key: 'skuPackage', label: 'label_sku_carton_spec', 'width': 120, if: () => this.TOB && this.SkuOutbound,
            formatter: (r, c, v) => `${v}/` + this.$tt('label_box'),
          },
          {
            key: 'boxCount', label: 'label_outbound_box_count', 'min-width': 140, if: () => this.TOB,
            render: (h, { row }) => {
              if (this.SkuOutbound) {
                return (<el-input-number class="w_fill" value={row.boxCount} disabled={this.GET_TRACK_NUMBER_FAIL} step-strictly min={1}
                  max={Math.ceil((row.usableQty) / (row.skuPackage))} onInput={e => this.changeBoxCount(e, row)} />)
              } else {
                return row.boxCount
              }

            },
          },
          {
            key: 'skuCount', label: 'label_outbound_count', 'min-width': 140, if: () => this.SkuOutbound,
            render: (h, { row, index }) => {
              const value = row.skuCount
              if (!this.TOB) {
                return (<el-input-number class="w_fill" value={value} disabled={this.GET_TRACK_NUMBER_FAIL} step-strictly
                  min={1} max={(row.usableQty)}
                  onChange={e => {
                    this.$set(row, 'skuCount', e)
                    this.$set(this.form.detailList, index, row)
                  }} />)
              } else {
                return row.skuCount
              }
            },
          },

          {
            type: 'operate', width: 120, operate: [
              {
                label: "label_remove", class: "button_text_danger",
                disabled: () => this.GET_TRACK_NUMBER_FAIL,
                click: (row, i) => this.removeSku(row)
              },
            ]
          }
        ]
      },

      //目的仓库到产品路径
      products: [],
      intersection: [],
      intersectionIndex: 0
    };
  },

  created() {
    this.getWarehouseList()
  },


  computed: {
    TOB() {
      return this.form.bizType == 'TOB'
    },
    SkuOutbound() {
      return this.form.outboundProductType == 'PRODUCT_OUTBOUND'
    },
    GET_TRACK_NUMBER_FAIL() {
      return this.form.outStatus == "GET_TRACK_NUMBER_FAIL"
    },
    //判断当前产品是否支持保险
    ProductSupportInsurance() {
      const select_product = _.find(this.ProductList, it => it.productId == this.form.logisticsId)
      if (select_product) {
        return !!select_product.supportInsurance
      }
      return false
    },

    disabled_ullage() {
      return _.reduce(this.form.detailList, (sum, it) => this.$math_add(sum, it.skuCount), 0) <= 1
    },
    SALES_OUTBOUND() {
      return this.form.outType == "SALES_OUTBOUND"
    },
    ALLOCATE_OUTBOUND() {
      return this.form.outType == "ALLOCATE_OUTBOUND"
    },
    DESTROY_OUTBOUND() {
      return this.form.outType == "DESTROY_OUTBOUND"
    },

    HOME_DELIVERY() {
      return this.form.outboundMode == "HOME_DELIVERY"
    },
    TAKE_THEIR() {
      return this.form.outboundMode == "TAKE_THEIR"
    },
    EC_WAREHOUSE_DELIVERY() {
      return this.form.outboundMode == "EC_WAREHOUSE_DELIVERY"
    },
    LOGISTICS_TRANSFER() {
      return this.form.outboundMode == "LOGISTICS_TRANSFER"
    },
    Sum_Sku_DeclaredValue() {
      return _.reduce(this.form.detailList, (sum, it) => this.$math_add(sum, this.$math_mul(it.skuDeclaredValue ? it.skuDeclaredValue : 0, it.skuCount)), 0)
    },
  },
  methods: {
    clickAgreement(e) {
      e.stopPropagation()
      // this.$refs.ozon_agreement.show()
    },
    selectQuickAddress(item) {
      this.form.consignee = item.contacts
      this.form.consigneePhone = item.contactNumber
      this.form.country = item.countryCode
      this.form.province = item.province
      this.form.city = item.city
      this.form.postcode = item.postalCode
      this.form.address = item.addressDetail
    },
    warehouseChange(e) {
      if (e) {
        this.form.warehouseId = e.warehouseId
        this.form.warehouseCode = e.warehouseCode
        this.form.warehouseName = e.warehouseName
      } else {
        this.form.warehouseId = null
        this.form.warehouseCode = null
        this.form.warehouseName = null
      }
      this.productChange(null)
    },
    productChange(e) {
      if (e) {
        this.form.logisticsId = e.productId
        this.form.logisticsName = e.productName
        this.form.logisticsCode = e.productCode
      } else {
        this.form.logisticsId = null
        this.form.logisticsName = null
        this.form.logisticsCode = null
      }
      this.form.insuranceService = "N"
    },
    changeFBAWarehouse(e) {
      if (!e) e = { id: null, code: null, name: null }
      this.form.fbaWarehouseId = e.id
      this.form.fbaWarehouseCode = e.code
      this.form.fbaWarehouseName = e.name
    },
    changeWarehouseConfirm(e) {
      this.confirmClearBox(() => {
        this.warehouseChange(e)
      })
    },
    changeCustomer(e) {
      if (!e) e = { customerId: null, customerName: null, customerCode: null }

      this.confirmClearBox(() => {
        this.form.customerId = e.customerId
        this.form.customerName = e.customerName
        this.form.customerCode = e.customerCode
      })

    },
    checkBoxRow(it) {
      this.$set(it, 'error', {})
      let check = true
      if (!it.skuCount) {
        this.$set(it.error, "skuCount", "tip_can_no_empty")
        check = false
      }
      if (!this.$reg.PureNumber(it.skuCount)) {
        this.$set(it.error, 'skuCount', "tip_only_positive_pure_decimal")
        check = false
      }

      // else if (this.TOB && (Number(it.skuCount) % Number(it.skuPackage) != 0) && (Number(it.skuCount) != Number(it.usableQty))) {
      //   this.$set(it.error, 'skuCount', "tip_TOB_order_sku_count_only_cartonSpec")
      //   check = false
      // }
      return check
    },
    skuListValidator(r, v, cb) {
      if (v.length == 0) {
        return cb(this.$tt('tip_please_add_least_one_sku'))
      }
      let check = true
      v.forEach(it => {
        if (!this.checkBoxRow(it)) check = false
      })
      if (check) {
        cb()
      } else {
        cb(this.$tt('label_sku_specification_check_fail'))
      }
    },
    clickWarehouseSkuSelect() {
      if (!this.form.warehouseId) return this.$message.warning(this.$t('tip_please_select_first_type', { type: this.$t('label_outbound_warehouse') }))
      if (this.$refs.return_good_order_select) {
        this.$refs.return_good_order_select.show({
          bizType: this.form.bizType,
          warehouseId: this.form.warehouseId,
          warehouseName: this.form.warehouseName,
          warehouseCode: this.form.warehouseCode,
        })
      }

    },

    returnOrderSelect(list) {

      const returnOrderCodes = this.form.detailList.map(it => it.returnOrderCode)

      if (_.isArray(list)) {
        list.forEach(it => {
          if (!returnOrderCodes.includes(it.returnOrderCode)) {
            this.form.detailList.push(...it.detailList.map(d => {
              return {
                returnOrderCode: it.code,
                platformCode:it.platformCode,
                storeCode: it.shopId,
                skuId: d.skuId,
                skuBarcode: d.skuBarcode,
                skuOnlyCode: d.skuOnlyCode,
                skuNameCn: d.skuName,
                skuNameEn: d.skuNameEn,
                skuCount: d.skuReturnQuantity,
                usableQty: d.skuReturnQuantity,
                stockUsage: d.skuReturnQuantity,
                skuDeclaredValue: d.skuDeclaredValue,
                currencyCode: d.skuCurrencyCode,
                stockUsage: "REFUND_SALE",
                bizType: this.form.bizType,
                // skuPackage :d.skuId,
              }
            }))
          }

        })

        this.getPriorityTop(this.form.detailList)
        console.log(this.form.detailList)
      }



    },

    removeSkuAll() {
      // this.form.detailList.forEach(row => {
      //   if (row.id) this.form.removeDetailIds.push(row.id)
      // })
      this.form.detailList = []
    },
    removeSku(row) {
      let i = _.indexOf(this.form.detailList, row)
      if (i != -1) {
        // if (row.id) this.form.removeDetailIds.push(row.id)
        this.form.detailList.splice(i, 1)
      }
      this.getPriorityTop(this.form.detailList)
    },
    init_data_default(newParams) {
      this.form = _.cloneDeep(defaultObj)
      if (newParams.outType) this.form.outType = newParams.outType
      this.edit = !!newParams.edit
      if (this.edit) {
        if (newParams.id) {
          this.loading = true
          this.$ajax({
            url: this.$url['oms/OutboundDetailById'],
            method: 'post',
            data: { id: newParams.id },
            complete: () => {
              this.loading = false
            },
            success: (res) => {
              this.getPriorityTop(res.data.detailList)

              let obj = Object.assign({}, _.cloneDeep(defaultObj), res.data)

              // let new_data = {}
              if (obj.warehouseId && obj.detailList && obj.detailList.length > 0) {
                // new_data.warehouseId = obj.warehouseId
                // new_data.skuIds = _.join(obj.detailList.map(it => it.skuId), ',')
                // obj.detailList.forEach(it => {
                //   it.skuDeclaredValue = it.declaredValue
                //   it.usableQty = it.stockCount || 0
                //   it.boxCount = Math.ceil(Number(it.skuCount) / Number(it.skuPackage))
                // })

                // this.editOrgSkuIdList = obj.detailList.map(it => it.id)
                this.form = obj

                //if (!this.GET_TRACK_NUMBER_FAIL && this.SkuOutbound) {
                // this.alignment_sku_count()
                //}

              } else {
                obj.detailList = []
                this.form = obj
              }
              this.fixTabLabel()

            }
          })
        }
      }
      this.fixTabLabel()
    },
    fixTabLabel() {
      if (this.edit && !!this.form.id) {
        this.$emit("tagModifyLabel", {
          _key: 'label_name_code', name: this.$tt("label_edit_noown_destroy_outbound_order"),
          code: this.form.orderNo || ""
        })

      } else {
        this.$emit('tagModifyLabel', "label_new_noown_destroy_outbound_order")
      }
    },

    changeBizType(e) {
      this.confirmClearBox(() => {
        this.form.bizType = e
        if (e == 'TOC') {
          this.form.outboundProductType = "PRODUCT_OUTBOUND"
        } else if (e == 'TOB') {
          this.form.outboundProductType = "BOX_NO_OUTBOUND"
        }
      })
    },

    changeBoxCount(e, row) {
      if (Number.isNaN(Number(e))) return
      this.$set(row, 'skuCount', Math.min(this.$math_mul(e, row.skuPackage), Number(row.usableQty)))
    },
    confirmClearBox(fun) {
      if (_.isEmpty(this.form.detailList)) {
        fun()
      } else {
        this.$confirm(this.$tt('tip_this_operate_will_fill_empty_sku_list'), this.$tt('label_tip'), {
          type: 'warning'
        }).then(() => {
          this.removeSkuAll()
          fun()
        }).catch(() => {
        });
      }
    },

    submitBeforeDealWith() {
      let data = _.cloneDeep(this.form)
      if (data.insuranceService == 'Y') {
        if (_.isEmpty(data.insuranceAmount)) data.insuranceAmount = this.Sum_Sku_DeclaredValue
      } else {
        delete data.insuranceAmount
      }
      //提交前比较原sku列表，添加删除skuid
      // data.removeDetailIds = []

      // this.editOrgSkuIdList.forEach(id => {
      //   if (!data.detailList.some(sku => sku.id == id)) {
      //     data.removeDetailIds.push(id)
      //   }
      // })

      return data
    },
    changeInitOutboundMode() {
      if (this.form.outboundMode == 'HOME_DELIVERY') {
        this.form.takeDeliveryPerson = null
        this.form.takeDeliveryPersonPhone = null
        this.form.takeDeliveryTime = null

        this.form.ecPlatformWarehouseId = null
        this.form.ecPlatformWarehouse = null
        this.form.ecPlatformWarehouseAddr = null
        this.form.requireDeliveryTime = null

        this.form.transferLogisticsName = null
        this.form.transferConsigneePhone = null
        this.form.transferShippingAddress = null


      } else if (this.form.outboundMode == 'TAKE_THEIR') {
        this.form.consignee = null
        this.form.consigneePhone = null
        this.form.email = null
        this.form.companyName = null
        this.form.country = null
        this.form.province = null
        this.form.city = null
        this.form.postcode = null
        this.form.houseNumber = null
        this.form.address = null
        this.form.reserveAddress = null

        this.form.ecPlatformWarehouseId = null
        this.form.ecPlatformWarehouse = null
        this.form.ecPlatformWarehouseAddr = null
        this.form.requireDeliveryTime = null

        this.form.transferLogisticsName = null
        this.form.transferConsigneePhone = null
        this.form.transferShippingAddress = null

      } else if (this.form.outboundMode == 'EC_WAREHOUSE_DELIVERY') {


        this.form.email = null
        this.form.companyName = null
        this.form.country = null
        this.form.province = null
        this.form.city = null
        this.form.postcode = null
        this.form.houseNumber = null
        this.form.address = null
        this.form.reserveAddress = null

        this.form.takeDeliveryPerson = null
        this.form.takeDeliveryPersonPhone = null
        this.form.takeDeliveryTime = null

        this.form.transferLogisticsName = null
        this.form.transferConsigneePhone = null
        this.form.transferShippingAddress = null

      } else if (this.form.outboundMode == 'LOGISTICS_TRANSFER') {

        this.form.consignee = null
        this.form.consigneePhone = null
        this.form.email = null
        this.form.companyName = null
        this.form.country = null
        this.form.province = null
        this.form.city = null
        this.form.postcode = null
        this.form.houseNumber = null
        this.form.address = null
        this.form.reserveAddress = null

        this.form.takeDeliveryPerson = null
        this.form.takeDeliveryPersonPhone = null
        this.form.takeDeliveryTime = null

        this.form.ecPlatformWarehouseId = null
        this.form.ecPlatformWarehouse = null
        this.form.ecPlatformWarehouseAddr = null
        this.form.requireDeliveryTime = null
      }
    },
    submit(opEnum) {
      if (this.$clickFast()) return
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          this.changeInitOutboundMode()
          if (opEnum == 'Submit') {
            const h = this.$createElement;
            const h_logistics = this.form.logisticsId ?
              h('div', { class: 'flex_row' }, [`${this.$tt('label_logistics')} : ${this.$formatNameCode(this.form.logisticsName, this.form.logisticsCode)}`]) : null

            this.$msgbox({
              title: this.$tt('label_tip'),
              showCancelButton: true,
              message: h('div', [
                h('div', { class: 'flex_row' }, [`${this.$tt('label_outbound_warehouse')} : ${this.$formatNameCode(this.form.warehouseName, this.form.warehouseCode)}`]),
                h_logistics,
              ])
            }).then(() => {
              this.submitNet(opEnum == 'Submit' ?
                this.$url['oms/OutboundSaveAndSubmit'] :
                this.$url['oms/OutboundResubmit'])
            }).catch(() => {
            });
          } else {
            this.submitNet(opEnum == 'Save' ? this.$url['oms/OutboundSave'] :
              this.$url['oms/OutboundResubmit'])
          }
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },
    submitNet(url) {

      let data = this.submitBeforeDealWith()
      data.detailList.forEach(it => {
        it.declaredValue = it.skuDeclaredValue
      })

      this.$ajax({
        // url: "/oms-api/order/OutboundOrderRpc/saveAndSubmitOutboundOrder.json",
        url,
        method: 'post', type: 'json',
        data: data,
        loading: true,
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.return_emit(null, "reload")
          this.$emitPage('standard>outbound_manage', 'reload')
          this.return_page_back()
        }
      })

    },
    getWarehouseList() {
      this.loading = true
      this.$ajax({
        url: this.$url['fms/getLastProduct'],
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            let list = res.data.rows
            list = list.filter(it => it.endWarehouse).map(it => it.endWarehouse)
            this.WarehouseList = _.unionBy(_.concat(...list), it => it.warehouseId)

          }
        },
      })
    },
    getPriorityTop(detailList) {

      this.intersection = []
      this.intersectionIndex = 0

      this.form.logisticsId = ''
      this.loading = true
      this.$ajax({
        url: '/oms-api/property/OmsBaseCargoPropertyRpc/selectPage.json',
        data: { status: 'ENABLE', pageSize: 9999 },
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            // 获得交集
            this.intersection = res.data.rows.filter(x => detailList.some(y => y.cargoPropertyId === x.id))
            this.initProduct()
          }
        },
      })
    },
    initProduct() {
      this.loading = true
      const length = this.intersection.length
      let cargoPropertyId = null
      if (length > 0) {
        cargoPropertyId = this.intersection[this.intersectionIndex] ? this.intersection[this.intersectionIndex].id : null
      }
      this.$ajax({
        url: this.$url['fms/getLastProduct'],
        data: { cargoPropertyId },
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          if (!res.data || res.data.rows.length === 0) {
            // this.intersectionIndex++
            // if(this.intersectionIndex<=length){
            //   this.initProduct()
            // }
            this.ProductList = []
            return
          }
          if (res && res.data && res.data.rows) {
            this.ProductList = res.data.rows.filter(it =>
              it.endWarehouse && it.endWarehouse.some(w => w.warehouseId == this.form.warehouseId)
            )
          }
        },
      })
    },




  }
};

</script>
<style></style>
